package com.jwgf.smarowindingmachine_unity.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.google.android.material.textfield.TextInputLayout;
import com.jwgf.adapter.DensityUtils;
import com.jwgf.adapter.MultiItemTypeAdapter;
import com.jwgf.common.SuCommand;
import com.jwgf.decoration.SpaceItemDecoration;
import com.jwgf.itemviewdelegates.CraftSelectAttr;
import com.jwgf.itemviewdelegates.CraftSelectDelegate;
import com.jwgf.objectbox.ObjectBox;
import com.jwgf.objectbox.SpindleParameter;
import com.jwgf.smarowindingmachine_unity.R;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CraftExportDialog extends DialogFragment {
    private TextInputLayout name;
    private RecyclerView rv;
    private MultiItemTypeAdapter<Object> rvAdapter;
    private List<Object> exportCrafts = new ArrayList<>();

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View v = inflater.inflate(R.layout.craft_export_view, null);
        name = v.findViewById(R.id.craft_name);
        rv = v.findViewById(R.id.craft_recycler);
        final List<SpindleParameter> parameters = ObjectBox.get().boxFor(SpindleParameter.class).getAll();
        List list = new ArrayList();
        for (SpindleParameter parameter : parameters) {
            CraftSelectAttr attr = new CraftSelectAttr();
            attr.setCraftName(parameter.craftName);
            attr.setId(parameter.id);
            list.add(attr);
        }
        rvAdapter = new MultiItemTypeAdapter<Object>(getContext(), list);
        rvAdapter.addItemViewDelegate(new CraftSelectDelegate());
        rvAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (position == -1)
                    return;
                if (((CraftSelectAttr) rvAdapter.getDatas().get(position)).isSelected()) {
                    ((CraftSelectAttr) rvAdapter.getDatas().get(position)).setSelected(false);
                    exportCrafts.remove(parameters.get(position));
                } else {
                    ((CraftSelectAttr) rvAdapter.getDatas().get(position)).setSelected(true);
                    exportCrafts.add(parameters.get(position));
                }
                rvAdapter.notifyDataSetChanged();

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 1);
        rv.setLayoutManager(layoutManager);
        rv.addItemDecoration(new SpaceItemDecoration(DensityUtils.dp2px(2), DensityUtils.dp2px(2)));
        rv.setAdapter(rvAdapter);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("批次导出");
        builder.setView(v);
        builder.setPositiveButton("导出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (!TextUtils.isEmpty(name.getEditText().getText().toString())) {
                    if (!exportCrafts.isEmpty()) {
                        export(name.getEditText().getText().toString(), JSON.toJSONString(exportCrafts, true));
                    } else {
                        Toast.makeText(getContext(), "请选择要导出的批次！", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(getContext(), "文件名不能为空！", Toast.LENGTH_LONG).show();

                }
            }
        });

        return builder.create();
    }

    private void export(String fileName, String craft) {
        String[] paths = getExternalDevices();
        if (paths != null) {
            FileWriter writer;
            try {
                String dir = paths[0] + File.separator + "批次" + File.separator;
                File dirFile = new File(dir);
                if (!dirFile.exists()) {
                    dirFile.mkdirs();
                }
                File craftFile = new File(dir + fileName + ".cra");
                if (!craftFile.exists()) {
                    writer = new FileWriter(craftFile);
                    writer.write(craft);
                    writer.flush();
                    writer.close();
                } else {
                    Toast.makeText(getContext(), "文件名已存在，请修改文件名！", Toast.LENGTH_LONG).show();
                }

            } catch (IOException e) {
                Toast.makeText(getContext(), "批次导出失败！", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        } else {
            Toast.makeText(getContext(), "没有检测到U盘", Toast.LENGTH_LONG).show();
        }

    }

    private void createDir(String path) {
        //建立目录
        String mkdirs = "mkdir -p " + path;
        SuCommand.suClient(mkdirs);
    }

    private void writeFile(String fileName, String craft) {
        StringBuilder sb = new StringBuilder();
        sb.append("echo ");
        sb.append(craft);
        sb.append(" ");
        sb.append("> ");
        sb.append(fileName);
        SuCommand.suClient(sb.toString());
    }

    private String[] getExternalDevices() {
        ArrayList<String> pathList = new ArrayList<String>();
        String path;
        if (Build.VERSION.RELEASE.equals("6.0.1")){
            path = "/mnt/media_rw/usb1";
        } else {
            path = "/mnt/usb1";
        }

        File file1 = new File(path);
        if (file1.exists()) {
            if (file1.list().length > 0) {
                pathList.add(path);
            }

            if (pathList.size() != 0) {
                return pathList.toArray(new String[]{});
            } else {
                return null;
            }
        }
        return null;

    }
}
